import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class Test extends Component {
  static defaultProps = {
    name: '计数器'
  };

  constructor(props) {
    super(props);
    this.state = {number: 0}; //初始化默认的状态对象
    console.log('Counter 1. 初始化 props and state');
  }

  componentWillMount() {
    console.log('Counter 2. componentWillMount组件将要挂载'); //之后会调用render 生成虚拟dom 参考02ireact/react-dom
  }

  componentDidMount() {
    console.log('Counter 4. componentDidMount组件挂载完成');
  }

  shouldComponentUpdate(nextProps, nextState, nextContext) {
    console.log('Counter 5. shouldComponentUpdate询问组件是否需要更新');
    return true;
  }

  componentWillUpdate(nextProps, nextState, nextContext) {
    console.log('Counter 6. componentWillUpdate组件将要更新');
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log('Counter 7. componentDidUpdate组件更新完毕');
  }

  add = () => {
    this.setState({number: this.state.number + 1});
  };

  render() {
    console.log('Counter 3. render渲染，也就是挂载');
    return (
      <div style={{border: '5px solid red', padding: '5px'}}>
        <p>{this.state.number}</p>
        <button onClick={this.add}>+</button>
        {this.state.number % 2 === 0 && <SubCounter number={this.state.number}/>}
      </div>
    );
  }
}

class SubCounter extends Component {
  constructor(props) {
    super(props);
    this.state = {number: 0};
  }

  componentWillReceiveProps(nextProps, nextContext) {
    console.log('SubCounter 1. componentWillReceiveProps将要接受到新的属性');
  }

  //调用此方法的时候会把新的属性对象和新的状态对象传过来，只有变化时才触发，初始化的时候并不会(会触发WillMount)
  shouldComponentUpdate(nextProps, nextState, nextContext) {
    if (nextProps.number % 3 == 0) {
      return true;
    } else {
      return false;
    }
  }

  componentWillMount() {
    console.log('SubCounter 1 componentWillMount');
  }

  componentWillUnmount() { //整个实例都没了
    console.log('SubCounter -1 componentWillUnmount');
  }

  render() {

    return (
      <div style={{border: '1px solid blue'}}>
        <p>{this.props.number}</p>
      </div>
    )
  }
}

ReactDOM.render(<Test/>, window.root);
